package com.xinqi.modules.databank.v2.service.answer.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xinqi.common.base.response.R;
import com.xinqi.common.core.enums.CourseContentTypeEnum;
import com.xinqi.common.satoken.utils.LoginHelper;
import com.xinqi.common.base.enums.YesNoNumberEnum;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.modules.course.clazz.client.ClassStudentClient;
import com.xinqi.modules.course.clazz.dto.rsp.ClassStudentResultDTO;
import com.xinqi.modules.databank.dto.req.ResourceInteractionLogCreateDTO;
import com.xinqi.modules.databank.v2.convert.CourseResourceInteractionLogConvert;
import com.xinqi.modules.databank.v2.domain.CourseResourceEntity;
import com.xinqi.modules.databank.v2.domain.CourseResourceInteractionLogEntity;
import com.xinqi.modules.databank.v2.domain.CourseResourcePartEntity;
import com.xinqi.modules.databank.v2.manager.CourseResourceBaseManager;
import com.xinqi.modules.databank.v2.manager.CourseResourcePartManager;
import com.xinqi.modules.databank.v2.manager.ResourceInteractionLogManager;
import com.xinqi.modules.databank.v2.service.answer.ResourceInteractionLogService;
import com.xinqi.modules.databank.v2.service.student.ResourceStudentLogService;
import com.xinqi.modules.databank.v2.util.QuestionUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Optional;

/**
 * 学生答题记录-业务层
 * @author dzy
 */
@Service
@RequiredArgsConstructor
public class ResourceInteractionLogServiceImpl implements ResourceInteractionLogService {

    private final CourseResourceInteractionLogConvert resourceInteractionLogConvert;

    private final ResourceInteractionLogManager resourceInteractionLogManager;

    private final CourseResourceBaseManager courseResourceBaseManager;

    private final CourseResourcePartManager resourcePartManager;

    private final ResourceStudentLogService resourceStudentLogService;

    private final ClassStudentClient classStudentClient;

    /**
     * 添加学生答题记录
     * @author dzy
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean answerQuestion(ResourceInteractionLogCreateDTO create) {

        // 判断是否数据存在
        CourseResourceEntity resource = Optional.ofNullable(courseResourceBaseManager.getById(create.getContentId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));

        // 已结束 资料库 不可答题
        if (resource.getEndTime().isBefore(LocalDateTime.now())) {
            return true;
        }

        // 获取 主学生信息
        Long userId = LoginHelper.getUserId();
        ClassStudentResultDTO mainStudent = R.as(classStudentClient.findVirtualClassStudentByClassIdAndUserId(resource.getClassId(), userId));

        // 获取答题数据
        LambdaQueryWrapper<CourseResourceInteractionLogEntity> logWrapper = new LambdaQueryWrapper<>();
        logWrapper.eq(CourseResourceInteractionLogEntity::getContentId, create.getContentId());
        logWrapper.eq(CourseResourceInteractionLogEntity::getResourcePartId, create.getResourcePartId());
        logWrapper.eq(CourseResourceInteractionLogEntity::getStudentId, mainStudent.getStudentId());
        CourseResourceInteractionLogEntity answer = resourceInteractionLogManager.getOne(logWrapper);

        // 判断是否已答题
        CommonErrors.BAD_REQUEST.check(Objects.isNull(answer), "不可重复答题");

        // 获取题目数据
        CourseResourcePartEntity partEntity = getQuestionPart(create, resource.getContentType());
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(partEntity), "未获取到互动答题");

        // 生成提交答题数据
        CourseResourceInteractionLogEntity entity = resourceInteractionLogConvert.create(create);
        entity.setStudentId(mainStudent.getStudentId());
        entity.setStatus(YesNoNumberEnum.YES.getCode());
        entity.setIsRead(YesNoNumberEnum.YES.getCode());
        entity.setSubmitTime(LocalDateTime.now());
        QuestionUtil.calcScore(entity, partEntity.getQuestions());

        boolean flag = resourceInteractionLogManager.save(entity);

        // 更新学生总得分
        if (Objects.equals(CourseContentTypeEnum.DATA.getCode(), resource.getContentType())) {
            resourceStudentLogService.refreshStudentLog(create.getContentId(), mainStudent.getStudentId(), false);
        } else {
            resourceStudentLogService.refreshStudentLog(create.getContentId(), mainStudent.getStudentId(), true);
        }

        return flag;
    }

    // 获取 题目信息
    private CourseResourcePartEntity getQuestionPart(ResourceInteractionLogCreateDTO dto, Integer type) {
        if (Objects.equals(CourseContentTypeEnum.DATA.getCode(), type)) {
            LambdaQueryWrapper<CourseResourcePartEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CourseResourcePartEntity::getContentId, dto.getContentId());
            wrapper.eq(CourseResourcePartEntity::getResourceId, dto.getResourcePartId());
            return resourcePartManager.getOne(wrapper);
        } else if (Objects.equals(CourseContentTypeEnum.INTERACTIVE_VIDEO.getCode(), type)) {
            LambdaQueryWrapper<CourseResourcePartEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CourseResourcePartEntity::getId, dto.getResourcePartId());
            return resourcePartManager.getOne(wrapper);
        } else {
            return null;
        }
    }

}
